package com.wechat.api.util;

import com.alibaba.fastjson.JSONObject;
import com.wechat.api.config.WeChatConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

/**
 * 微信工具类
 */
@Slf4j
@Configuration
public class WeChatUtil {

    /**
     *  请求微信平台
     * @param requestUrl
     * @return
     */
    public static String httpRequest(String requestUrl){
        return httpRequest(requestUrl,"GET",null);
    }

    /**
     *  请求微信平台
     * @param requestUrl
     * @param requestMethod
     * @return
     */
    public static String httpRequest(String requestUrl,String requestMethod){
        return httpRequest(requestUrl,requestMethod,null);
    }

    /**
     *  请求微信平台
     * @param requestUrl
     * @param requestMethod
     * @param output
     * @return
     */
    public static String httpRequest(String requestUrl,String requestMethod,String output){
        try{
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if(null != output){
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            connection.disconnect();
            return buffer.toString();
        }catch(Exception e){
            log.error(e.toString());
        }
        return "";
    }

    /**
     * json格式转Get
     * @param body
     * @return
     */
    public static String jsonToGet(String body){
        return body.replace("{", "").replace("}", "").
                replace("\"", "").replace("'", "").
                replace(":", "=").replace(",", "&");
    }
}
